package marcus.jpa.dao;

import java.util.List;

import marcus.jpa.entities.Contact;
import marcus.jpa.entities.User;
import marcus.jpa.hibernate.HibernateUtil;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

public class ContactsDao {
	public static List<User> getUsers(){
		SessionFactory sf = HibernateUtil.getSessionFactory();
	    Session session = sf.openSession();
		List<User> users = session.createQuery("from User").list();
		session.close();
		
		return users;
	}

	public static User getUser(String name){
		SessionFactory sf = HibernateUtil.getSessionFactory();
	    Session session = sf.openSession();
		Query query = session.createQuery("from User where name = :name");
		query.setString("name", name);
		User user = (User)query.list().get(0);
		session.close();
		
		return user;
	}

	public static List<Contact> getContacts(User user){
		SessionFactory sf = HibernateUtil.getSessionFactory();
	    Session session = sf.openSession();
	    Query query = session.createQuery("from Contact where id.userKey = :key");
	    query.setString("key", user.getUserKey());
	    
		List<Contact> contacts = query.list();
		session.close();
		
		return contacts;
	}
	
	public static void updateContact(Contact contact){
		SessionFactory sf = HibernateUtil.getSessionFactory();
	    Session session = sf.openSession();
	    Transaction tx = session.beginTransaction();
	    session.update(contact);
	    tx.commit();
	    session.close();
	}
	
}
